package com.jl.resolver;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.alibaba.fastjson.JSONObject;

/**
 * @author caijunhao
 * @version 创建时间：2020年10月12日 下午3:48:40 类说明
 */
public class RequestBodyArgumentResolver implements HandlerMethodArgumentResolver {

	private static final String JSON_REQUEST_BODY = "JSON_REQUEST_BODY";

	// 判断是否支持要转换的参数类型
	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return false;
	}

	// 当支持后进行相应的转换
	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
		Class paramObjClass = parameter.getParameterType();
		String body = getRequestBody(webRequest);
		Object paramObj = paramObjClass.newInstance();
		Object object = JSONObject.parseObject(body, paramObjClass);
		return object != null ? object : paramObj;
	}

	private String getRequestBody(NativeWebRequest webRequest) {
		HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
		String jsonBody = (String) servletRequest.getAttribute(JSON_REQUEST_BODY);
		if (jsonBody == null) {
			try {
				jsonBody = IOUtils.toString(servletRequest.getInputStream());
				servletRequest.setAttribute(JSON_REQUEST_BODY, jsonBody);
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		return jsonBody;

	}

}
